<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/3/27
 * Time: 17:50
 */

namespace app\index\controller;


use app\service\DepositService;
use Protocol\Curl;
use Redis\Redis;
use think\Db;

class Mine extends Common
{

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 我的
     */
    function index()
    {
        if (!empty($this->employeeId)) {
            # 员工登录
            $serviceNumSql = '(select count(id) from orders where order_status=5 and 
             order_number in (select order_number from order_server where find_in_set(' . $this->employeeId . ',employee_id))) store_service_num';
        } else {
            # 老板登录
            $serviceNumSql = '(select count(id) from orders where biz_id=biz.id and order_status = 5) store_service_num';
        }
        # 查询门店信息
        $bizInfo = Db::table('biz')
            ->field('*,biz_title store_name,' . $serviceNumSql)
            ->where(array('id' => $this->bizId))
            ->find();
        # 客服电话
        $bizInfo['service_tel'] = '400-8045288';
        # 查询门店标签'
        # 判断门店类型
        $biz_where = "id in (select class_pid from service where id in (select service_id from service_biz where biz_id = " . $this->bizId . "))";
        if ($bizInfo['biz_type'] == 1) {
            $biz_where = '';
        }
        /*$biz_tags = Db::table('service_class sc')
            ->field('concat_ws(",",service_class_pid,id) biz_tags')
            ->where($biz_where)
            ->find()['biz_tags'];*/
        $bizInfo['biz_tags'] = Db::table('service_class sc')
            ->field('group_concat(distinct service_class_title) biz_tags')
//            ->where("id in (" . $biz_tags . ")")
            ->where($biz_where)
            ->where("service_class_pid = 0 and is_del = 2")
            ->find()['biz_tags'];
        # 结算比例
        $bizInfo['comment_rate_settlement'] = config('ecarcoo.comment_rate_settlement');
        $bizInfo['comment_rate_settlement']['good'] = ($bizInfo['comment_rate_settlement']['good'] * 100) . '%';
        $bizInfo['comment_rate_settlement']['medium'] = ($bizInfo['comment_rate_settlement']['medium'] * 100) . '%';
        $bizInfo['comment_rate_settlement']['bad'] = ($bizInfo['comment_rate_settlement']['bad'] * 100) . '%';
        $bizInfo['custom_service_royalty'] = $bizInfo['extract_selfservice'];
        $bizInfo['custom_pro_royalty'] = $bizInfo['extract_selfpro'];
        # 查询今日提成排行榜(第一名)(员工是否参与排名)
        $deduct = Db::table('deduct d')
            ->field('employee_head head_pic,employee_name name,format(coalesce(sum(deduct),0),2) as income,sum(deduct) as deduct')
            ->join('employee e', 'd.employee_id=e.id', 'left')
            ->where(array('e.ranking_status' => 1, 'e.biz_id' => $this->bizId))
            ->where("date(`create`)='" . date('Y-m-d') . "' and deduct > 0")
            ->group('d.employee_id')
            ->order(array('deduct' => 'desc'))
            ->find();
        if (!empty($deduct)) {
            $deduct['head_pic'] = imgUrl($deduct['head_pic']);
            $resArr['day_mvp'] = $deduct;
        } else {
            $resArr['day_mvp'] = array('name' => '', 'head_pic' => '');
        }
        #   查询月度评论得分排行第一名
        $evalua = Db::table('evaluation_score es')
            ->field('employee_name name,employee_head head_pic,sum(es.score) fraction_num')
            ->join('employee e', 'e.id=es.employee_id', 'left')
            ->where(array('e.biz_id' => $this->bizId, 'e.scores_ranking' => 1))
            ->where("date_format(es.create_time,'%Y-%m')='" . date('Y-m') . "'")
            ->group('es.employee_id')
            ->order(array('fraction_num' => 'desc'))
            ->find();
        if (!empty($evalua)) {
            $evalua['head_pic'] = imgUrl($evalua['head_pic']);
            $resArr['month_mvp'] = $evalua;
        } else {
            $resArr['month_mvp'] = array("name" => '', "head_pic" => '');
        }
        # 门店名称
        $resArr['store_name'] = $bizInfo['store_name'];
        # 门店服务次数
        $resArr['store_service_num'] = $bizInfo['store_service_num'];
        # 门店待结算金额  'desposit_status'=>1,
        $resArr['toBeSettledAmount'] = getsPriceFormat(Db::table('biz_settlement')
                ->where(array('biz_id' => $this->bizId, 'settlement_status' => 1, 'mark' => 1))->sum('price') +
            Db::table('biz_settlement')
                ->where(array('biz_id' => $this->bizId, 'settlement_status' => 1, 'desposit_status' => 1, 'mark' => 1))->sum('commission_price')
        );
        if ($this->bizId == 428 or $this->bizId == 429 or $this->bizId == 673) {
            $resArr['toBeSettledAmount'] += $bizInfo['security_price'];
            if($this->bizId==429){
                $resArr['toBeSettledAmount'] += 17853.21;
                $bizInfo['security_price'] += 17853.21;
            }
            if($this->bizId==673){
//                $resArr['toBeSettledAmount'] += 22192.41;
                $resArr['toBeSettledAmount'] += 19192.41;
                $bizInfo['security_price'] += 19192.41;
            }
        }
//        if ($bizInfo['settlement_count'] >= $bizInfo['security_price']) {
//            $resArr['toBeSettledAmount'] += $bizInfo['security_price'];
//        } else {
//            $bizInfo['security_price'] = $resArr['toBeSettledAmount'];
//        }
//        $resArr['toBeSettledAmount']+=$bizInfo['security_price'];
        # 门店联系方式
        $resArr['biz_phone'] = $bizInfo['biz_phone'];
        # 查询门店消息数量
        $resArr['newsCount'] = Db::table('biz_news_mapping bnm')
            ->where("bnm.biz_id = $this->bizId and bnm.status=1")->count();
//        $resArr['newsCount']=0;
        # 门店余额
        $resArr['balance'] = $bizInfo['account_balance'];
        # 员工信息
        $employeeInfo = array();
        if (!empty($this->employeeId)) {
            $employeeInfo = Db::table('employee')->where(array('id' => $this->employeeId))->find();
            $employeeInfo['employee_head'] = imgUrl($employeeInfo['employee_head']);
//            $employeeInfo['jobs_info'] = Db::table('jobs')->where(array('id'=>$employeeInfo['jobs_id']))->find()['jobs_title'];
        }
        $bizInfo['biz_head'] = imgUrl($bizInfo['biz_img']);
        $time = date('Y-m-d H:i:s');
        # 任务
        $bizTask = Db::table('cooperative_task_list')
            ->where(array('biz_id' => $this->bizId))
            ->where("status != 3 and status != 4")
            ->count();
        $task = Db::table('cooperative_task')
            ->where("start_time <= '" . $time . "' and end_time > '" . $time . "'")
            ->where("id not in 
            (select task_id from cooperative_task_list where (status = 1 or status = 2) and biz_id = " . $this->bizId . ")")
            ->where("id not in 
            (select task_id from cooperative_task_list ct left join cooperative_task c on ct.task_id=c.id
             where (status = 3 or status = 4) and is_loop=1 and biz_id = '" . $this->bizId . "')")
            ->count();
        if ($bizInfo['biz_type'] == 1) {
            $bizMember = false;
        } else {
            $bizMember = false;//true
        }
        # 推荐会员
        $recommend = array('imgUrl' => imgUrl('static/advertisement/recommend.png', true) . '?1', 'version' => '1.2.7', 'isJump' => false, 'bizMember' => $bizMember);
        # APP推荐下载码
        $downloadApp = imgUrl('static/advertisement/download_new.png', true) . '?1';
        # 分享文案
        $shareInfo = config('ecarcoo.shareWx');
        $shareInfo['summary'] = $bizInfo['store_name'] . $shareInfo['summary'];
        $shareInfo['shareImg'] = $bizInfo['biz_img'];
        return array('status' => true, 'data' => $resArr, 'bizInfo' => $bizInfo, 'employeeInfo' => $employeeInfo,
            'task' => $bizTask + $task, 'share' => $shareInfo, 'recommend' => $recommend, 'downLoad' => $downloadApp);

    }

    /**
     * @return array|mixed|string
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @content 设置头像
     */
    function setUpPicture()
    {
        # 接收图片
        $imgInfo = input('post.imgInfo');
        if (empty($imgInfo)) {
            return array('status' => false, 'msg' => '图片信息为空');
        }
        # 上传图片
        $res = uploadBase($imgInfo,'creation');
        if (is_array($res)) {
            return $res;
        }
        if (!empty($this->employeeId)) {
            # 修改员工头像
            Db::table('employee')->where(array('id' => $this->employeeId))->update(array('employee_head' => $res));
        } else {
            # 门店门头照
            Db::table('biz')->where(array('id' => $this->bizId))->update(array('biz_head' => $res,'biz_img'=>$res));
        }
        return array('status' => true);
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 设置页面信息
     */
    function setUpInfo()
    {
        # 查询门店营业时间和手机号
        $bizInfo = Db::table('biz')
            ->field('biz_opening start_time,biz_closing end_time,biz_phone phone,open_state')
            ->where(array('id' => $this->bizId))
            ->find();
        # 查询门店工位信息
        $workStation = Db::table('station')
            ->field('id work_id,station_title title')
            ->where(array('biz_id' => $this->bizId))
            ->order(array('id' => 'asc'))
            ->select();
        if (!empty($workStation)) {
            # 查询门店工位对应的员工信息
            foreach ($workStation as $k => $v) {
                $workStation[$k]['staff'] = Db::table('employee')
                    ->field('id staff_id,employee_name staff_name')
                    ->where('find_in_set(id,(select employee_id from station_staff where station_id = ' . $v['work_id'] . '))')
                    ->where("employee_status != 0")
                    ->select();
            }
        }
        $employeeInfo = array();
        $phone = $bizInfo['phone'];
        if (!empty($this->employeeId)) {
            $employeeInfo = Db::table('employee e')->join('employee_mapping em', 'e.id=em.employee_id', 'left')->where(array('e.id' => $this->employeeId))->find();
            $attend_select = Db::table("log_attendance")->where("employee_id=" . $this->employeeId . " 
                            and  date_format(create_time,'%Y-%m')='" . date('Y-m') . "'")->count();
            $employeeInfo['attend'] = date('d') - $attend_select;
            $phone = $employeeInfo['employee_phone'];
        }
        # 合作协议Url
        $cooperation_agreement = Db::table("application")->field('application_uri')
            ->where(array("application_class" => "protocol", 'application_mark' => 'cooperation_agreement'))->find();
        if (!empty($cooperation_agreement)) {
            $cooperation_agreement = $cooperation_agreement['application_uri'];
        } else {
            $cooperation_agreement = '';
        }
        # 关于E联车服
        $cooperation_ecars = Db::table("application")->field('application_uri')
            ->where(array("application_class" => "protocol", 'application_mark' => 'cooperation_ecars'))->find();
        if (!empty($cooperation_ecars)) {
            $cooperation_ecars = $cooperation_ecars['application_uri'];
        }
        $_return = array(
            'start_time' => $bizInfo['start_time'],
            'end_time' => $bizInfo['end_time'],
            'phone' => $phone,
            'work_list' => $workStation,
            'employeeInfo' => $employeeInfo,
            'introduce' => $cooperation_ecars,
            'cooperationAgreement' => $cooperation_agreement,
            'open_state' => $bizInfo['open_state']
        );
        return array('status' => true, 'data' => $_return);
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 门店员工好评排行
     */
    function getPraiseRank()
    {
        # 接收月份
        $month = input('post.month');
        if (!empty($month)) {
            $_where = 'date_format(es.create_time,"%Y-%m")="' . $month . '"';
        } else {
            $_where = 'date_format(es.create_time,"%Y-%m")="' . date('Y-m') . '"';
        }
        # 查询好评排行信息
        $info = Db::table('evaluation_score es')
            ->field('sum(es.score) fraction_num,employee_name title,jobs_info position')
            ->join('employee e', 'e.id=es.employee_id', 'left')
            ->where(array('e.biz_id' => $this->bizId, 'e.scores_ranking' => 1))
            ->where($_where)
            ->group('es.employee_id')
            ->order(array('fraction_num' => 'desc'))
            ->select();
        if (!empty($info)) {
            foreach ($info as $k => $v) {
                $info[$k]['rank'] = $k;
            }
        }
        return array('status' => true, 'data' => $info);
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 员工收入排行
     */
    function getIncomeRank()
    {
        # 接收岗位id
        $jobsId = input('post.position_title');
        if (!empty($jobsId) and !is_null($jobsId) and $jobsId != '全部岗位') {
            $_where = " e.jobs_info  = '" . $jobsId . "'";
        } else {
            $_where = '';
        }
        # 接收日期搜索
        $_day = input('post.day');
        if (!empty($_day)) {
            $_daySearch = 'date(d.create)="' . $_day . '"';
        } else {
            $_daySearch = 'date(d.create)="' . date('Y-m-d') . '"';
        }
        #查询参与排名的所有员工的岗位
        $jobsInfo = Db::table('employee e')
            ->field('distinct jobs_info position_title')
            ->join('deduct d', 'd.employee_id=e.id', 'left')
            ->where(array('e.ranking_status' => 1, 'e.biz_id' => $this->bizId))
            ->where("employee_status != 0 and del_status = 1 and jobs_info != '' ")
            ->select();
        array_unshift($jobsInfo, array('position_title' => '全部岗位'));
        # 根据员工分组查询提成总和,进行排名
        $rankingInfo = Db::table('deduct d')
            ->field('employee_name title,employee_head head_pic,jobs_info position_title,format(coalesce(sum(deduct),0),2) income')
            ->join('employee e', 'e.id=d.employee_id', 'left')
            ->where($_daySearch)
            ->where($_where)
            ->where("deduct >= 0")
            ->where("employee_status != 0 and del_status = 1")
            ->where(array('e.ranking_status' => 1, 'e.biz_id' => $this->bizId))
            ->group('d.employee_id')
            ->select();
        if (!empty($rankingInfo)) {
            foreach ($rankingInfo as $k => $v) {
                $rankingInfo[$k]['head_pic'] = imgUrl($v['head_pic']);
            }
            array_multisort(array_column($rankingInfo, 'income'), SORT_DESC, $rankingInfo);
        }
        return array('status' => true, 'data' => array('positionInfo' => $jobsInfo, 'rankingInfo' => $rankingInfo));
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 车辆服务记录
     */
    function getCarService()
    {
        $pageNum = input('post.page_num') ?? 0;
        $size = input('post.size') ?? 10;
        $limit = $pageNum * $size;
        $where = '';
        if ($this->loginType == 2) {
            # 员工登录
            $where = "o.order_number in (select order_number from order_server where find_in_set(" . $this->employeeId . ",employee_id))";
        }
        # 查询门店服务记录(查询订单已完成的)
        $orderInfo = Db::table('orders o')
            ->field('order_number,o.voucher_price,
            case pay_type 
                            when 1 then \'微信支付\'
                            when 2 then \'支付宝支付\'
                            when 3 then \'银联支付\' 
                            when 4 then \'现金支付\'
                            when 5 then \'余额支付\'
                            when 6 then \'卡券支付\' end mode,
            order_over time,if(pay_type=6,0,pay_price) pay_price,car_liences car_num,pay_type,
            if(o.member_car_id=0,o.car_level,(select `level` from car_sort cs  right join member_car mc on mc.car_type_id = cs.id where mc.id = o.member_car_id)) car_level,
if(o.member_car_id=0,(select sort_title from car_sort cs where cs.id = o.car_sort),
  (select sort_title from car_sort cs right join member_car mc on mc.car_type_id = cs.id where mc.id = o.member_car_id)) sort_title,
if(o.member_car_id=0,(select title from car_logo cl where cl.id = o.car_logo),
  (select title from car_logo cl right join car_sort cs on cs.logo_id = cl.id right join member_car mc on mc.car_type_id = cs.id where mc.id = o.member_car_id)) logo_title,
if(o.member_car_id=0,(select level_title from car_level cl where cl.id = o.car_level),
  (select level_title from car_level cl right join car_sort cs on cs.level = cl.id right join member_car mc on mc.car_type_id = cs.id where mc.id = o.member_car_id)) carType,
  o.evaluation_status score_mark,
  (select score from evaluation_score where order_id=o.id limit 1) score,
            (SELECT biz_title from biz where id=o.biz_id) service_coo,
            (SELECT member_phone from member where id=o.member_id) phone,
            IFNULL((SELECT level_title from member_level where id=(SELECT member_level_id from member_mapping where member_id=o.member_id)),"普通用户") member_title,
            (if(pay_type=6,(select sum(original_price) from order_server where order_number = o.order_number),(SELECT format(coalesce(sum(voucher_price),0),2) from log_cashcoupon lc where lc.order_number=o.order_number))) discount_price
            ')
            ->where(array('biz_id' => $this->bizId, 'order_status' => 5))
            ->where($where)
            ->order(array('o.id' => 'desc'))
            ->limit($limit, $size)
            ->select();
        if (!empty($orderInfo)) {
            foreach ($orderInfo as $k => $v) {
                if ($v['discount_price'] == 0) {
                    $orderInfo[$k]['discount_price'] = getsPriceFormat($v['voucher_price']);
                }
                if ($v['score_mark'] == 1) {
                    $orderInfo[$k]['score_info'] = '未评论';
                } else {
                    if ($v['score'] == 5) {
                        $orderInfo[$k]['score_info'] = '好评';
                    } elseif ($v['score'] == 3) {
                        $orderInfo[$k]['score_info'] = '中评';
                    } else {
                        if ($v['score'] === 0) {
                            $orderInfo[$k]['score_info'] = '差评';
                        } else {
                            $orderInfo[$k]['score_info'] = '未评论';
                        }
                    }
                }
                $orderInfo[$k]['brand_model'] = $v['sort_title'] . "-" . $v['logo_title'];
                $orderInfo[$k]['total_price'] = $v['pay_price'] + $v['discount_price'];
                # 商品工单
                $orderBiz = Db::table('order_biz ob')
                    ->field('if(ob.custommark=1,(select biz_pro_title from biz_pro bp where bp.id=ob.biz_pro_id limit 1),
                    (select custom_biz_title from custom_biz cb where cb.id=ob.biz_pro_id limit 1)) service_title,bizpro_number num,
                    if(' . $v['pay_type'] . '=5,ob.pro_price,ob.original_pro_price) price')
                    ->where(array('order_number' => $v['order_number']))
                    ->buildSql();
                # 查询该订单下的服务工单
                $temporary = Db::table('order_server os')
                    ->field('if(os.custommark=1,(select (CASE WHEN LENGTH(service_title)>12
    THEN CONCAT(SUBSTRING(service_title,1,12),\'...\') 
    ELSE service_title END)
  from service s where s.id=os.server_id limit 1),
                    (select (CASE WHEN LENGTH(custom_server_title)>12
    THEN CONCAT(SUBSTRING(custom_server_title,1,12),\'...\') 
    ELSE custom_server_title END) from customserver cs where cs.id =os.server_id limit 1)) service_title,(select count(id) from order_server where server_id=os.server_id and custommark=os.custommark and order_number = os.order_number) num,
                    if(' . $v['pay_type'] . '=5,os.price+os.coupon_price,if(os.original_price>0,os.original_price,os.price+os.coupon_price)) price')
                    ->where(array('order_number' => $v['order_number']))
                    ->union([$orderBiz])
                    ->buildSql();
                # 联合查询
                $orderInfo[$k]['service_list'] = Db::table($temporary . 't')->select();
            }
        }
        return array('status' => true, 'data' => $orderInfo);
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 门店结算记录(待结算金额,结算记录(未结算/已结算)(时间倒序)(每次查询 5 条))
     */
    function logSettlement()
    {
        # 接收页码
        $pageNum = input('post.page_num') ?? 0;
        $length = 10;
        $size = intval($pageNum) * $length;
        # 状态筛选(1未结算  2已结算)
        $status = input('post.status') ?? 1;
        # 查询该门店待结算金额
        $settlementAmount = getsPriceFormat(Db::table('biz_settlement')
                ->where(array('biz_id' => $this->bizId, 'settlement_status' => $status, 'mark' => 1))->sum('price') +
            Db::table('biz_settlement')
                ->where(array('biz_id' => $this->bizId, 'settlement_status' => $status, 'desposit_status' => 1, 'mark' => 1))->sum('commission_price'));
        # 查询门店余额
        $bizInfo = Db::table('biz')->field('account_balance,security_price,settlement_count')->where(array('id' => $this->bizId))->find();
        if ($this->bizId == 428 or $this->bizId == 429 or $this->bizId == 673) {
            $settlementAmount += $bizInfo['security_price'];
            if($this->bizId==429){
                $settlementAmount += 17853.21;
                $bizInfo['security_price'] += 17853.21;
            }
            if($this->bizId==673){
//                $settlementAmount += 22192.41;
                $settlementAmount += 19192.41;
                $bizInfo['security_price'] += 19192.41;
            }
        }
//        if ($bizInfo['settlement_count'] >= $bizInfo['security_price']) {
//            $settlementAmount += $bizInfo['security_price'];
//        }
        # 查询结算记录(每次查询10条)
        $logInfo = Db::table('biz_settlement bs')
            ->field("bs.member_id,bs.order_number,bs.price price,bs.commission_price,
            tobe_settled total_price,bs.method type_mark,desposit_status,negative_price,
            (case bs.type when 1 then '门店订单' when 2 then '推荐收益'when 3 then '用户升级' when 4 then '用户充值' end ) as `type`,
            (case bs.method when 2 then '支付宝支付' when 1 then '微信支付' when 4 then '现金支付' when 3 then '银联支付' 
                         when 6 then '卡券核销'when 5 then '余额支付' end)  `method`,type typeInfo,
             bs.create_time,bs.order_price,bs.coupon_price,bs.commission_price,if(bs.settlement_status=1,'未结算','已结算') status
             
             ")
            ->where(array('bs.biz_id' => $this->bizId, 'desposit_status' => $status, 'mark' => 1))
//            ->where("bs.order_number=o.order_number")
            ->order(array('bs.create_time' => 'desc'))
            ->limit($size, $length)
            ->select();
        if (!empty($logInfo)) {
            foreach ($logInfo as $k => $v) {
                $logInfo[$k]['commission_price'] += $v['negative_price'];
                if ($v['desposit_status'] == 2) {
                    $logInfo[$k]['status'] = '已结算';
                }
                $orderInfo = Db::table('orders o')
                    ->field("o.pay_price,o.order_over,car_liences,m.member_phone,mp.member_level_id,
             if(ml.level_title is null || ml.level_title ='','普通用户',level_title) level_title,
             (select default_mark from evaluation_score where order_id=o.id limit 1) score_mark,
              (select score from evaluation_score where order_id=o.id limit 1) score
             ")
                    ->join('member m', 'o.member_id=m.id', 'left')
                    ->join('member_mapping mp', 'm.id=mp.member_id', 'left')
                    ->join('member_level ml', 'ml.id=mp.member_level_id', 'left')
                    ->where(array('o.order_number' => $v['order_number']))
                    ->find();
                if (!empty($orderInfo)) {
                    $logInfo[$k]['pay_price'] = $orderInfo['pay_price'];
                    $logInfo[$k]['order_over'] = $orderInfo['order_over'];
                    $logInfo[$k]['car_liences'] = $orderInfo['car_liences'];
                    $logInfo[$k]['member_phone'] = $orderInfo['member_phone'];
                    $logInfo[$k]['member_level_id'] = $orderInfo['member_level_id'];
                    $logInfo[$k]['level_title'] = $orderInfo['level_title'];
                    $logInfo[$k]['score_mark'] = $orderInfo['score_mark'];
                    $logInfo[$k]['score'] = $orderInfo['score'];
                    $v['pay_price'] = $orderInfo['pay_price'];
                    $v['order_over'] = $orderInfo['order_over'];
                    $v['car_liences'] = $orderInfo['car_liences'];
                    $v['member_phone'] = $orderInfo['member_phone'];
                    $v['member_level_id'] = $orderInfo['member_level_id'];
                    $v['level_title'] = $orderInfo['level_title'];
                    $v['score_mark'] = $orderInfo['score_mark'];
                    $v['score'] = $orderInfo['score'];
                }else{
                    $v['score_mark'] = 1;
                }
                if ($v['score_mark'] == 1 or is_null($v['score_mark'])) {
                    $logInfo[$k]['score_info'] = '中评';
                    $logInfo[$k]['score'] = 3;
                    $logInfo[$k]['score_mark'] = 2;
                } else {
                    if (is_null($v['score'])) {
                        $logInfo[$k]['score'] = 3;
                        $logInfo[$k]['score_info'] = '中评';
                    } else {
                        if ($v['score'] == 5) {
                            $logInfo[$k]['score_info'] = '满意';
                        } else if ($v['score'] < 3) {
                            if ($v['score'] === 0) {
                                $logInfo[$k]['score_info'] = '不满意';
                            } else {
                                $logInfo[$k]['score_info'] = '未评论';
                            }
                        } else {
                            $logInfo[$k]['score_info'] = '中评';
                        }
                    }
                }
                if ($v['typeInfo'] == 1) {
                    # 查询商品工单
                    $orderBiz = Db::table('order_biz ob')
                        ->field("ob.id,ob.referrer,ob.employee_id,2 orderType,status,if(" . $v['desposit_status'] . "=2,final_settlement,price_settlement) price_settlement,
                    if(" . $v['type_mark'] . "=5,ob.pro_price,ob.original_pro_price) price,ob.bizpro_number num,
                (select group_concat(employee_name) from employee e where find_in_set(e.id,ob.referrer)) referrer_name,
                (select group_concat(employee_name) from employee e where find_in_set(e.id,ob.employee_id)) employee_name,
                if(ob.custommark=1,'系统商品','自定义商品') type,
                if(ob.custommark = 1,(select biz_pro_title from biz_pro bp where bp.id = ob.biz_pro_id limit 1),
                (select custom_biz_title from custom_biz cb where cb.id = ob.biz_pro_id limit 1)) title,
                case ob.status 
                      when 1 then '未结算'
                      when 2 then '已完成'
                      when 3 then '已完成'
                end serviceStatus,
                if(station_id is null,'',(select station_title from station s where s.id = ob.station_id)) workNums,
                if(station_id is null,'',station_id) workNum,
                (select score from evaluation_score where orderserver_id=ob.id and type=2 limit 1) score,
                (select default_mark from evaluation_score where orderserver_id=ob.id and type=2 limit 1) score_mark
                ")
                        ->where(array('order_number' => $v['order_number']))
                        ->buildSql();
                    # 查询服务工单 if(" . $v['type_mark'] . "=5,os.price+os.coupon_price,os.original_price) price
                    $orderServer = Db::table('order_server os')
                        ->field("os.id,os.referrer,os.employee_id,1 orderType,status,if(" . $v['desposit_status'] . "=2,final_settlement,price_settlement) price_settlement,
                    os.original_price price,1 num,
                (select group_concat(employee_name) from employee e where find_in_set(e.id,os.referrer)) referrer_name,
                (select group_concat(employee_name) from employee e where find_in_set(e.id,os.employee_id)) employee_name,
                if(os.custommark=1,'系统服务','自定义服务') type,
                if(os.custommark=1,(select service_title from service s where s.id=os.server_id limit 1),
                   (select custom_server_title from customserver cs where cs.id=os.server_id limit 1)) title,
                   case status
                        when 1 then '未开始'
                        when 2 then '服务中'
                        when 3 then '已完成'
                        when 4 then '已完成'
                        when 5 then '等待中'
                        when 6 then '已完成'
                   end serviceStatus,
                   if(station_id is null,'',(select station_title from station s where s.id = os.station_id)) workNums,
                   if(station_id is null,'',station_id) workNum ,
                   (select score from evaluation_score where orderserver_id=os.id and type=1 limit 1) score,
                   (select default_mark from evaluation_score where orderserver_id=os.id and type=1 limit 1) score_mark
                ")
                        ->where(array('order_number' => $v['order_number']))
                        ->union([$orderBiz])
                        ->buildSql();
                    $logInfo[$k]['order_detail'] = Db::table($orderServer . 'tem')->select();
                    $logInfo[$k]['order_price'] = array_sum(array_column($logInfo[$k]['order_detail'], 'price'));
                } else {
                    $logInfo[$k]['pay_price'] = $logInfo[$k]['order_price'];
                    $phone = Db::table('member')->field('member_phone')->where(array('id' => $v['member_id']))->value('member_phone');
                    $logInfo[$k]['member_phone'] = $phone;
                    if ($v['typeInfo'] == 2) {
                        $title = '推荐收益';
                        $levelTitle = Db::table('member_level')->field('level_title')->where(array('id' => $v['order_number']))->value('level_title');
                    } elseif ($v['typeInfo'] == 3) {
                        $title = '用户升级';
                        $levelTitle = Db::table('member_level')->field('level_title')->where(array('id' => explode(',', $v['order_number'])[1]))->value('level_title');
                    } else {
                        $levelTitle = '会员充值';
                        $title = '用户充值';
                    }
                    $logInfo[$k]['levelTitle'] = $levelTitle;
                    $logInfo[$k]['order_detail'] = array(array('title' => $levelTitle, 'num' => 1, 'level_title' => $levelTitle, 'price' => $logInfo[$k]['order_price'], 'price_settlement' => $logInfo[$k]['order_price']));
                }
            }
        }
        return array('status' => true, 'data' => array('settlementAmount' => $settlementAmount, 'logInfo' => $logInfo));
    }


    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @content 修改门店营业时间
     */
    function ModifyBusinessHours()
    {
        $hour = input('post.hour');
        $mark = input('post.mark');
        if ($mark == 'open') {
            # 修改门店营业起始时间
            Db::table('biz')->where(array('id' => $this->bizId))->update(array('biz_opening' => $hour));
        } elseif ($mark == 'close') {
            # 修改门店营业结束时间
            Db::table('biz')->where(array('id' => $this->bizId))->update(array('biz_closing' => $hour));
        } elseif ($mark == 'restore') {
            # 恢复营业(open_state=>1 , 正常营业)
            Db::table('biz')->where(array('id' => $this->bizId))->update(array('open_state' => 1));
        } else {
            # 临时打烊(open_state=>2,暂停营业)
            Db::table('biz')->where(array('id' => $this->bizId))->update(array('open_state' => 2));
        }
        return array('status' => true, 'msg' => '修改成功');
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 查询门店工位信息
     */
    function bizStation()
    {
        # 查询门店工位列表(同时查询员工姓名)
        $info = Db::table('station s')
            ->field('s.id,s.station_title,
            (select group_concat(employee_name) from employee where del_status = 1 and employee_status != 0 and  find_in_set(id,ss.employee_id)) employee_name,
            (select group_concat(id) from employee where del_status = 1 and employee_status != 0 and  find_in_set(id,ss.employee_id))
            employee_id')
            ->join('station_staff ss', 'ss.station_id=s.id', 'left')
            ->where(array('s.biz_id' => $this->bizId))
            ->order(array('id' => 'asc'))
            ->select();
        if (!empty($info)) {
            foreach ($info as $k => $v) {
                if (!empty($v['employee_id'])) {
                    $info[$k]['employee_id'] = explode(',', $v['employee_id']);
                }
            }
        }
        return array('status' => true, 'msg' => '查询成功', 'info' => $info);
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @content 修改工位 团队人员
     */
    function bizStationStaff()
    {
        # 选择的员工(英文逗号分隔)
        $employee_id = input('post.employee_id');
        # 工位id
        $station_id = input('post.station_id');
        if (!empty($station_id)) {
            # 先查
            $info = Db::table('station_staff')->field('id')->where(array('station_id' => $station_id))->find();
            if (empty($info)) {
                Db::table('station_staff')->insert(array('station_id' => $station_id, 'employee_id' => $employee_id, 'create_time' => date('Y-m-d H:i:s')));
            } else {
                Db::table("station_staff")->where(array("station_id" => $station_id))->update(array('employee_id' => $employee_id));
            }
            $this->_Redis->hDel('stationEmployee', strval($station_id));
            return array('status' => true, 'msg' => '修改成功');
        }
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 查询本月提成(员工登录/老板登录)
     */
    function commission()
    {
        # 接收页码
        $pageNum = input('post.page_num') ?? 0;
        $length = 10;
        $size = intval($pageNum) * $length;
        # 查询员工提成
        # 接收时间(格式 : 2020-01)
        $time = input('post.time');
        if (empty($time)) {
            $time = date('Y-m');
        }
        # 接收员工id
        $where = "";
        $employeeId = $this->employeeId;
        if (!empty($employeeId)) {
            $where = "d.employee_id = " . $employeeId;
        } else {
            $where = "d.employee_id = 0";
        }
        $info = Db::table('deduct d')
            ->field('d.id,d.order_number,sum(d.deduct) deduct,date_format(d.create,"%Y-%m-%d %H:%i") time,type,d.order_server_id,
            o.car_liences carNum,o.order_over,
            if(o.member_car_id=0,(select sort_title from car_sort cs where cs.id = o.car_sort),
  (select sort_title from car_sort cs right join member_car mc on mc.car_type_id = cs.id where mc.id = o.member_car_id)) sort_title,
if(o.member_car_id=0,(select title from car_logo cl where cl.id = o.car_logo),
  (select title from car_logo cl right join car_sort cs on cs.logo_id = cl.id right join member_car mc on mc.car_type_id = cs.id where mc.id = o.member_car_id)) logo_title,
  if(o.member_car_id=0,(select level_title from car_level cl where cl.id = o.car_level),
  (select level_title from car_level cl right join car_sort cs on cs.level = cl.id right join member_car mc on mc.car_type_id = cs.id where mc.id = o.member_car_id)) carType,
  o.order_price,(select default_mark from evaluation_score where order_id=o.id limit 1) score_mark,(select score from evaluation_score where order_id=o.id limit 1) score,
  if(o.member_id = 0,"普通用户",(select level_title from member_level ml where ml.id = (select member_level_id from member_mapping where member_id = o.member_id))) vipGrade
            ')
            ->join('orders o', 'o.order_number = d.order_number', 'left')
            ->where("date_format(d.create,'%Y-%m') = '" . $time . "' and d.biz_id = " . $this->bizId)
            ->where($where)
            ->group('d.order_number')
            ->order(array('d.id' => 'desc'))
            ->limit($size, $length)
            ->select();
//        dump( Db::table('deduct d')->getLastSql());
        # 总提成
        if ($pageNum == 0) {
            $totalDeduct = Db::table('deduct d')->where("date_format(d.create,'%Y-%m') = '" . $time . "' and d.biz_id = " . $this->bizId)->where($where)->sum('deduct');
        } else {
            $totalDeduct = 0;
        }
        if (!empty($info)) {
            foreach ($info as $k => $v) {
                //. '-' . $v['carType']
                $info[$k]['car_info'] = $v['logo_title'] . '-' . $v['sort_title'];
                if ($v['score_mark'] == 1) {
                    $info[$k]['score_info'] = '未评论';
                    if ($v['order_over'] <= date('Y-m-d H:i:s', strtotime('-1 day'))) {
                        $info[$k]['score_info'] = '中评';
                    }
                } else {
                    if ($v['score'] == 0) {
                        $info[$k]['score_info'] = '不满意';
                    } elseif ($v['score'] == 3) {
                        $info[$k]['score_info'] = '中评';
                    } else {
                        $info[$k]['score_info'] = '满意';
                    }
                }
                if ($v['type'] == 1) {
                    $info[$k]['typeInfo'] = '商品提成';
                } elseif ($v['type'] == 2) {
                    $info[$k]['typeInfo'] = '服务提成';
                } elseif ($v['type'] == 3) {
                    $info[$k]['car_info'] = Db::table('member_level')->field('level_title')->where(array('id' => $v['order_number']))->value('level_title');
                    $info[$k]['carNum'] = Db::table('member')->field('member_phone')->where(array('id' => $v['order_server_id']))->value('member_phone');
                    $info[$k]['typeInfo'] = '推荐用户';
                    $info[$k]['score_info'] = '';
                } elseif ($v['type'] == 4) {
                    $id = explode(',', $v['order_number']);
                    $info[$k]['car_info'] = Db::table('member_level')->field('level_title')->where(array('id' => $id[1]))->value('level_title');
                    $info[$k]['carNum'] = Db::table('member')->field('member_phone')->where(array('id' => $v['order_server_id']))->value('member_phone');
                    $info[$k]['typeInfo'] = '用户升级';
                    $info[$k]['score_info'] = '';
                } elseif ($v['type'] == 5) {
                    $info[$k]['car_info'] = '用户充值';
                    $info[$k]['carNum'] = Db::table('member')->field('member_phone')->where(array('id' => $v['order_server_id']))->value('member_phone');
                    $info[$k]['typeInfo'] = '用户充值';
                    $info[$k]['score_info'] = '';
                }
            }
        }
        //getsPriceFormat(array_sum(array_column($info, 'deduct')))
        return array('status' => true, 'msg' => '查询成功', 'info' => $info, 'totalDeduct' => $totalDeduct);
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 提成详情
     */
    function commissionDetail()
    {
        # 接收订单编号
        $orderNumber = input('post.order_number');
        # 接收提成类型(1->服务  2->商品 3->办理会员)(办理会员时)
        $type = input('post.type');
        if (!empty($orderNumber)) {
            if ($type != 3) {
                if (!empty($this->employeeId)) {
                    $server_sql = "(select sum(deduct) deduct from deduct d where order_number = os.order_number and type = 2 and order_server_id = os.id and d.employee_id=" . $this->employeeId . " )";//limit 1
                    $biz_sql = "(select sum(deduct) deduct from deduct d where order_number = ob.order_number and type = 1 and order_server_id = ob.id and d.employee_id=" . $this->employeeId . ")";
                    $emplpyeeId = "find_in_set($this->employeeId,employee_id)";
                } else {
                    $server_sql = '(select sum(deduct) deduct from deduct d where order_number = os.order_number and type = 2 and order_server_id = os.id )';
                    $biz_sql = '(select sum(deduct) deduct from deduct d where order_number = ob.order_number and type = 1 and order_server_id = ob.id )';
                    $emplpyeeId = "";
                }
                # 查询订单详情
                # 查询商品工单
                $orderBiz = Db::table('order_biz ob')
                    ->field("(ob.pro_price - ob.coupon_price) price,bizpro_number num,(select date_format(order_over,'%Y-%m-%d %H:%i') from orders where order_number = '" . $orderNumber . "') `time`,
                if(ob.custommark=1,'系统商品','自定义商品') type,
                if(ob.custommark = 1,(select biz_pro_title from biz_pro bp where bp.id = ob.biz_pro_id limit 1),
                (select custom_biz_title from custom_biz cb where cb.id = ob.biz_pro_id limit 1)) title,
                " . $biz_sql . " deduct,
                (select score from evaluation_score where orderserver_id=ob.id and type=2 limit 1) score,
                (select default_mark from evaluation_score where orderserver_id=ob.id and type=2 limit 1) score_mark
                ")
                    ->where(array('order_number' => $orderNumber))
                    ->where($emplpyeeId)
                    ->buildSql();
                # 查询服务工单
                $orderServer = Db::table('order_server os')
                    ->field("os.price,1 num,date_format(os.order_end,'%Y-%m-%d %H:%i') `time`,
                if(os.custommark=1,'系统服务','自定义服务') type,
                if(os.custommark=1,(select service_title from service s where s.id=os.server_id limit 1),
                   (select custom_server_title from customserver cs where cs.id=os.server_id limit 1)) title,
                   " . $server_sql . " deduct,
                   (select score from evaluation_score where orderserver_id=os.id and type=1 limit 1) score,
                   (select default_mark from evaluation_score where orderserver_id=os.id and type=1 limit 1) score_mark
                ")
                    ->where(array('order_number' => $orderNumber))
                    ->where($emplpyeeId)
                    ->unionAll([$orderBiz])
                    ->buildSql();
                $orderDetail = Db::table($orderServer . 'tem')->select();
                if (!empty($orderDetail)) {
                    foreach ($orderDetail as $k => $v) {
                        if ($v['score_mark'] == 1) {
                            $orderDetail[$k]['score_info'] = '未评论';
                            if ($v['time'] <= date('Y-m-d H:i', strtotime('-1 day'))) {
                                $orderDetail[$k]['score_info'] = '中评';
                            }
                        } else {
                            if ($v['score'] == 0) {
                                $orderDetail[$k]['score_info'] = '不满意';
                            } elseif ($v['score'] == 3) {
                                $orderDetail[$k]['score_info'] = '中评';
                            } else {
                                $orderDetail[$k]['score_info'] = '满意';
                            }
                        }
                    }
                }
            } else {
                # 办理会员
                $orderDetail = Db::table('deduct d')
                    ->field("ml.level_practical price,date_format(d.create,'%Y-%m-%d %H:%i') time,'推荐用户' type,d.deduct,ml.level_title title,5 score,''score_info")
                    ->join('member_level ml', 'd.order_server_id=ml.id', 'left')
                    ->where(array('order_number' => $orderNumber))
                    ->where("d.biz_id = " . $this->bizId)
                    ->limit(1)
                    ->select();
            }
            return array('status' => true, 'msg' => '查询成功', 'info' => $orderDetail);
        } else {
            return array('status' => false, 'msg' => '参数信息为空');
        }
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 门店服务记录(订单信息)
     */
    function orderInfo()
    {
        $page = input('post.page') ? input('post.page') : 0;
        $listRows = 10;
        $pageMark = $page * $listRows;
        # 查询已完成的订单信息
        $orderInfo = Db::table('orders o')
            ->field("o.id,o.order_number,
            if(o.car_liences is null or o.car_liences ='',(select car_licens from member_car where id = o.member_car_id),o.car_liences) license,m.member_phone,
            if(mm.member_level_id = 0 or mm.member_level_id is null,'普通用户',ml.level_title) level_title,date_format(o.order_over,'%Y年%m月%d日 %H:%分') time,
            pay_price,order_price,voucher_price")
            ->join('biz b', 'o.biz_id=b.id', 'left')
            ->join('member m', 'm.id=o.member_id', 'left')
            ->join('member_mapping mm', 'o.member_id=mm.member_id', 'left')
            ->join('member_level ml', 'mm.member_level_id=ml.id', 'left')
            ->where(array('o.biz_id' => $this->bizId, 'o.order_status' => 5))
            ->order(array('o.id' => 'desc'))
            ->limit($pageMark, $listRows)
            ->select();
        return array('status' => true, 'msg' => '查询成功', 'info' => $orderInfo);
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 订单下的服务和商品
     */
    function orderDetail()
    {
        $orderNumber = input('post.order_number');
        if (!empty($orderNumber)) {
            # 查询订单下的所有服务列表
            $orderServer = Db::table('order_server os')
                ->field("price,if(custommark=1,(select service_title from service where id = os.server_id),
                (select custom_server_title from customserver where id = os.server_id)) title , 1 num,'服务' type")
                ->where(array('order_number' => $orderNumber))
                ->select();
            # 查询订单下的商品
            $orderBiz = Db::table('order_biz ob')
                ->field("pro_price price,if(custommark=1,(select biz_pro_title from biz_pro where id = ob.biz_pro_id),
                (select custom_biz_title from custom_biz where id =ob.biz_pro_id)) title,bizpro_number num,'商品' type")
                ->where(array('order_number' => $orderNumber))
                ->select();
            $_info = array_merge($orderServer, $orderBiz);
            return array('status' => true, 'msg' => '查询成功', 'info' => $_info);
        } else {
            return array('status' => false, 'msg' => '参数存在空值');
        }
    }

    /**
     * @return array
     * @content 退出登录
     */
    function exitLogin()
    {
        # 判断是老板登录还是员工登录
        if ($this->loginType == 1) {
            # 老板登录
            #删除缓存
            $this->_Redis->hDel('redis', "redis_bizId" . $this->bizId);
        } else {
            # 员工登录
            $employeeInfo = $this->_Redis->hGetJson('redis', "redis_employee" . $this->bizId);
            # 删除登录的员工信息
            array_splice($employeeInfo, array_search($this->employeeId, $employeeInfo), 1);
            $this->_Redis->hSetJson('redis', "redis_employee" . $this->bizId, $employeeInfo);
        }
        return array('status' => true, 'msg' => '退出登录成功!');
    }

    /**
     * @return array
     * @throws \Yansongda\Pay\Exceptions\BusinessException
     * @throws \Yansongda\Pay\Exceptions\GatewayException
     * @throws \Yansongda\Pay\Exceptions\InvalidArgumentException
     * @throws \Yansongda\Pay\Exceptions\InvalidSignException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content  门店发起提现
     */
    function withdraw()
    {
        # 门店余额提现
        # 提现金额
        $amount = input('post.amount');
        # 收款人姓名
        $payee_name = input('post.payee_name');
        # 收款人账号
        $payee_account = input('post.payee_account');
        //return array('status' => false, 'grantStatus' => false, 'msg' => '系统错误,请稍后再试');
        # 每周二、周五可操作提现，其余时间不可提现。
        $date_N = date('N');
        if($date_N != 2 and $date_N != 5){
            return array('status' => false, 'msg' => '每周二、周五可操作提现 ，其余时间不可提现！');
        }
        if ($this->bizId == 438) {
            return array('status' => false, 'msg' => '平台升级中暂时无法提现！');
        }
        if (!empty($amount) and !empty($payee_name) and !empty($payee_account)) {
            # 查询门店信息
            $bizInfo = Db::table('biz')
                ->field('biz_leader,biz_phone,area')
                ->where(array('id' => $this->bizId))
                ->find();
            if($bizInfo['area']=='鲅鱼圈区' and $this->bizId != 692){
                return array('status' => false, 'msg' => '平台升级中暂时无法提现！');
            }
            if ($bizInfo['biz_leader'] != $payee_name) {
                return array('status' => false, 'msg' => '收款姓名填写有误');
            }
            # 提现金额100的整数倍
            if ($amount % 100 != 0) {
                return array('status' => false, 'msg' => '提现金额必须是100的整数倍');
            }
            # 判断余额是否充足
            $bizInfo = Db::table('biz')->field('account_balance balance,biz_phone,province,city,area,biz_address')->where(array('id' => $this->bizId))->find();
            if ($bizInfo['balance'] < $amount) {
                return array('status' => false, 'grantStatus' => false, 'msg' => '余额不足');
            }
//            if (empty($bizInfo['openid'])) {
//                return array('status' => false, 'grantStatus' => true, 'msg' => 'openid为空,请先授权');
//            }
            # 添加提现记录
            $logId = Db::table('log_deposit')->insertGetId(array(
                'biz_id' => $this->bizId,
                'create_time' => date('Y-m-d H:i:s'),
                'price' => $amount,
                'username' => $payee_name,
                'phone' => $bizInfo['biz_phone'],
                'account_name' => $payee_name,
                'account_code' => $payee_account,
                'launch_cate' => 3,
                'deposit_type' => 2,
                'province' => $bizInfo['province'],
                'city' => $bizInfo['city'],
                'area' => $bizInfo['area'],
                'address' => $bizInfo['biz_address']
            ));
            # 扣除余额
            Db::table('biz')->where(array('id' => $this->bizId))->setDec('account_balance', $amount);
            Db::table('biz')->where(array('id' => $this->bizId))->update(array('deposit_account' => $payee_account, 'biz_leader' => $payee_name));
            # 进行提现
//            $payment = new Payment([
//                'partner_trade_no' => $orderNumber,              //商户订单号
//                'openid' => $bizInfo['openid'],                        //收款人的openid---oU1MG1nnH71SGTUTAY8Q7KK0POKY
//                'check_name' => 'FORCE_CHECK',            //NO_CHECK：不校验真实姓名\FORCE_CHECK：强校验真实姓名
//                're_user_name' => $payee_name,              //check_name为 FORCE_CHECK 校验实名的时候必须提交
//                'amount' => '1',                       //企业付款金额，单位为分
//                'desc' => 'E联车服帐户提现',                  //付款说明
//            ]);
//            $res = $payment->transfers();
//            if ($res['status'] and $res['returnCode'] == 'SUCCESS') {
            # 提现成功,修改提现记录状态
//                Db::table('log_withdraw')->where(array('id' => $logId))->update(array('status' => 2, 'arrive_time' => $res['payment_time'], 'payment_no' => $res['payment_no']));
//
//            } else {
//                if ($res['returnCode'] == 'PROCESSING') {
//                    # 处理中
//                    $msg = '处理中';
//                } else {
//                    $msg = $res['reason'];
//                }
//            }
            return array('status' => true, 'msg' => '处理中');
        } else {
            return array('status' => false, 'grantStatus' => false, 'msg' => '参数信息为空');
        }
    }

    /**
     * @return array
     * @throws \Yansongda\Pay\Exceptions\GatewayException
     * @throws \Yansongda\Pay\Exceptions\InvalidArgumentException
     * @throws \Yansongda\Pay\Exceptions\InvalidSignException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 门店余额提现记录
     */
    function logWithDraw()
    {
        $pageNum = input('post.pageNum');
        $size = 20;
        if (!empty($pageNum)) {
            $limit = $pageNum * $size;
        } else {
            $limit = 0;
        }
        # 查询提现记录
        $info = Db::table('log_deposit')
            ->field('id,date_format(create_time,"%Y-%m-%d %H:%i") time,price amount,deposit_status,
            (case deposit_status when 1 then \'等待审核\' when 2 then \'等待提现\' when 3 then \'提现成功\' when 4 then \'提现失败\' when 5 then \'审核驳回\' end ) as `statusInfo`')
            ->where(array('biz_id' => $this->bizId))
            ->order(array('create_time' => 'desc'))
            ->limit($limit, $size)
            ->select();
        /*  if (!empty($info)) {
              # 更新处理中的订单的状态
              foreach ($info as $k => $v) {
                  if ($v['status'] == 1) {
                      if (!empty($v['trade_no'])) {
                          $find = new Payment([
                              'partner_trade_no' => $v['trade_no']
                          ]);
                          $findRes = $find->findOrderInfo();
                          if ($findRes['returnCode'] == 'SUCCESS') {
                              # 成功
                              $info[$k]['status'] = 2;
                              $info[$k]['statusInfo'] = '提现成功';
                              Db::table('log_withdraw')->where(array('id' => $v['id']))->update(array('status' => 2, 'arrive_time' => $findRes['payment_time'], 'payment_no' => $findRes['payment_no']));
                          } elseif ($findRes['returnCode'] == 'FAILED') {
                              # 失败
                              $info[$k]['status'] = 3;
                              $info[$k]['statusInfo'] = '提现失败';
                              Db::table('log_withdraw')->where(array('id' => $v['id']))->update(array('status' => 3, 'arrive_time' => $findRes['payment_time'], 'payment_no' => $findRes['payment_no']));
                          } elseif ($findRes['returnCode'] == 'PROCESSING') {
                              # 处理中
                              continue;
                          }
                      }
                  }
              }
          }*/
        $balance = Db::table('biz')->field('account_balance')->where(array('id' => $this->bizId))->value('account_balance');
        return array('status' => true, 'msg' => '查询成功', 'info' => $info, 'balance' => $balance);
    }

    /**
     * @return array|false[]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @context 获取合作店推荐任务
     */
    function getsBizRecommendTask()
    {
        # 查询总开关
        $switch = Db::table("switch")->where(array("switch_type" => "recommendaward", "switch_status" => 1))->find();
        if (empty($switch)) {
            return array("status" => false);
        }
        $award = Db::table("recommend_award")->where(array("status" => 1))
            ->where("start_time<='" . date("Y-m-d H:i:s") . "' and end_time>'" . date("Y-m-d H:i:s") . "'")
            ->find();
        if (empty($award)) {
            return array("status" => false);
        }
        # 查询该门店今日是否有推荐任务
        $info = Db::table("recommend_biz")
            ->where(array("biz_id" => $this->bizId, "create_time" => date("Y-m-d")))->find();
        if (empty($info)) {
            $info = DepositService::addBizTask($this->bizId);
        }
        if (!empty($info)) {
            return array("status" => true, "info" => $info);
        } else {
            return array("status" => false);
        }

    }

    /**
     * @return array
     * @throws \Yansongda\Pay\Exceptions\BusinessException
     * @throws \Yansongda\Pay\Exceptions\GatewayException
     * @throws \Yansongda\Pay\Exceptions\InvalidArgumentException
     * @throws \Yansongda\Pay\Exceptions\InvalidSignException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @context 提现到微信
     */
    function depositWx()
    {
        $redis = new Redis();
        $noRepeat = $redis->lock("recommendDeposit" . $this->bizId, 3);
        if (!$noRepeat) {
            return array("status" => false, "msg" => "操作过于频繁，请稍后再试");
        }
        # 查询是否有openid
        $bizInfo = Db::table("biz")->field("openid,biz_title")->where(array("id" => $this->bizId))->find();
        if (!empty($bizInfo['openid'])) {
            # 查询账户余额是否>1
            $accountInfo = Db::table("recommend_biz")->where(array("biz_id" => $this->bizId, "create_time" => date("Y-m-d")))->find();
            if (!empty($accountInfo)) {
                if (!empty($accountInfo['earn_balance']) and $accountInfo['earn_balance'] >= 1) {
                    # 查询今日提现是否超过每日限额
                    $depositLogPrice = Db::table("recommend_log_deposit")->where(array("biz_id" => $this->bizId))
                        ->where("date(create_time)='" . date("Y-m-d") . "' and status in (1,3)")->sum("deposit_price");
                    if ($depositLogPrice < $accountInfo['max_earn'] and ($depositLogPrice + floatval($accountInfo['earn_balance'])) <= floatval($accountInfo['max_earn'])) {
                        $payStatus = DepositService::startDeposit($bizInfo['openid'], $accountInfo['earn_balance'], $this->bizId);
                        if ($payStatus['status']) {
                            # 提现成功
                            DepositService::depositSuccess($accountInfo['id'], $this->bizId, $accountInfo['earn_balance'], $payStatus['order_number'], $bizInfo['biz_title'], 0);
                            return array("status" => true, "return_code" => 1, "msg" => "提现成功,1-3个工作日内转账到微信余额，敬请关注");
                        } else {
                            if ($payStatus['code'] == 404) {
                                # 微信系统故障
                                return array("status" => false, "msg" => "微信提现系统故障,请稍后再试");
                            } else {
                                # 提现失败进入等待
                                DepositService::depositFail($accountInfo['id'], $this->bizId, $accountInfo['earn_balance'], $payStatus['order_number'], $bizInfo['openid'], $bizInfo['biz_title']);
                                return array("status" => true, "return_code" => 2, "msg" => "提现成功,1-3个工作日内转账到微信余额，敬请关注");
                            }
                        }
                    } else {
                        return array("status" => false, "msg" => "今日提现已超过限额");
                    }
                } else {
                    return array("status" => false, "msg" => "账户余额不足");
                }
            } else {
                return array("status" => false, "msg" => "提现账户信息错误");
            }
        } else {
            return array("status" => false, "msg" => "账户信息错误");
        }
    }

    /**
     * @return bool[]
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @context 更新门店openid
     */
    function updateBizOpenid()
    {
        $openid = input("post.openid");
        Db::table("biz")->where(array("id" => $this->bizId))->update(array("openid" => $openid));
        return array("status" => true);
    }


}
